package com.zhy.sample_okhttp;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.cookie.CookieJarImpl;

import okhttp3.Call;
import okhttp3.CookieJar;
import okhttp3.Request;
import okhttp3.Response;
import xcrash.XCrash;

public class MainActivity extends AppCompatActivity {
    private String mBaseUrl = "http://192.168.31.242:8888/okHttpServer/";

    private static final String TAG = "MainActivity";

    private TextView mTv;
    private View webViewFy;
    private ProgressBar mProgressBar;
    private String cookieStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTv = (TextView) findViewById(R.id.id_textview);
        mTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        webViewFy = findViewById(R.id.webViewFy);
        mProgressBar = (ProgressBar) findViewById(R.id.id_progress);
        mProgressBar.setMax(100);
    }

    public void loginFun(View view) {
        OkHttpUtils.post().url("http://router.asus.com/login.cgi")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Origin", "http://router.asus.com")
                .addHeader("Host", "router.asus.com")
                .addHeader("Cookie", "clickedItem_tab=1")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .addHeader("Referer", "http://router.asus.com/Main_Login.asp")
                .addHeader("Accept-Encoding", "gzip, deflate")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addParams("group_id", "")
                .addParams("action_mode", "")
                .addParams("action_script", "")
                .addParams("action_wait", "5")
                .addParams("current_page", "Main_Login.asp")
                .addParams("next_page", "index.asp")
                .addParams("login_authorization", Base64Utils.encode("test:123456".getBytes()))
                .addParams("login_captcha", "")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(final Response response, int id) throws Exception {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String cookieTmp = response.header("Set-Cookie");
                                mTv.setText("parseNetworkResponse===>Code:" + response.code() + ";Cookie:" + cookieTmp);
                                if(!TextUtils.isEmpty(cookieTmp))cookieStr = cookieTmp;
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, final Exception e, int id) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText("onError:" + e.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {
                        //mTv.setText("onResponse:" + response);
                    }
                });
    }

    public void logoutFun(View view) {
        OkHttpUtils.get().url("http://router.asus.com/Logout.asp")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Pragma", "no-cache")
                .addHeader("Host", "router.asus.com")
                .addHeader("Cookie", "f'"+cookieStr+"; clickedItem_tab=0'")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .addHeader("Accept-Encoding", "gzip, deflate")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .id(101)
                .build()
                .execute(new MyStringCallback());
    }

    public void getHtml(View view) {
        OkHttpUtils.get().url("http://router.asus.com/Advanced_System_Content.asp")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                .id(100)
                .build()
                .execute(new MyStringCallback());
    }

    public void openSSH(View view) {
        OkHttpUtils.post().url("http://router.asus.com/start_apply.htm")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Origin", "http://router.asus.com")
                .addHeader("Host", "router.asus.com")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                .addHeader("Accept", "text/javascript,application/javascript,application/ecmascript,application/x-ecmascript,*/*;q=0.01")
                .addHeader("Referer", "http://router.asus.com/Main_Login.asp")
                .addHeader("Accept-Encoding", "gzip, deflate")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Pragma", "no-cache")
                .addHeader("X-Requested-With", "XMLHttpRequest")

                .addParams("modified", "0")
                .addParams("action_mode", "apply")
                .addParams("action_script", "restart_time;restart_upnp")
                .addParams("action_wait", "5")
                .addParams("first_time", "")
                .addParams("sshd_enable", "1")// 1-开启 0-关闭
                .addParams("sshd_authkeys", "888")
                .addParams("sshd_port", "22")
                .addParams("sshd_pass", "1")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(final Response response, int id) throws Exception {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText("parseNetworkResponse===>Code:" + response.code());
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, final Exception e, int id) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText("onError:" + e.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {
                        //mTv.setText("onResponse:" + response);
                    }
                });
    }

    public void closeSSH(View view) {
        OkHttpUtils.post().url("http://router.asus.com/start_apply.htm")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Origin", "http://router.asus.com")
                .addHeader("Host", "router.asus.com")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                .addHeader("Accept", "text/javascript,application/javascript,application/ecmascript,application/x-ecmascript,*/*;q=0.01")
                .addHeader("Referer", "http://router.asus.com/Main_Login.asp")
                .addHeader("Accept-Encoding", "gzip, deflate")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Pragma", "no-cache")
                .addHeader("X-Requested-With", "XMLHttpRequest")

                .addParams("modified", "0")
                .addParams("action_mode", "apply")
                .addParams("action_script", "restart_time;restart_upnp")
                .addParams("action_wait", "5")
                .addParams("first_time", "")
                .addParams("sshd_enable", "0")// 1-开启 0-关闭
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(final Response response, int id) throws Exception {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText("parseNetworkResponse===>Code:" + response.code());
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, final Exception e, int id) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText("onError:" + e.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {
                        //mTv.setText("onResponse:" + response);
                    }
                });
    }

    public void getHomeShow(View view) {
        /*OkHttpUtils.get().url("http://router.asus.com/Main_Login.asp")//"http://192.168.50.1/")//"http://router.asus.com")//
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                .id(100)
                .build()
                .execute(new MyStringCallback());*/
        loadWebPageHtml(true);
    }

    public void getHomeHide(View view) {
        loadWebPageHtml(false);
    }

    public void clearSession(View view) {
        CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar();
        if (cookieJar instanceof CookieJarImpl) {
            ((CookieJarImpl) cookieJar).getCookieStore().removeAll();
        }
    }

    private void loadWebPageHtml(boolean isShow){
        AgentWeb mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((ViewGroup) webViewFy, new FrameLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(new WebViewClient(){
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        view.loadUrl("javascript:window.java_obj.onHtml('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
                    }
                })
                .createAgentWeb()
                .ready()
                .go("http://router.asus.com");
        mAgentWeb.getJsInterfaceHolder().addJavaObject("java_obj", new JavaObjectJsInterface());
        webViewFy.setVisibility(isShow ? View.VISIBLE : View.INVISIBLE);
    }

    public class JavaObjectJsInterface {
        @JavascriptInterface // 要加这个注解，不然调用不到
        public void onHtml(String html) {
            mTv.setText(html);
        }
    }

    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(Request request, int id)
        {
            setTitle("loading...");
        }

        @Override
        public void onAfter(int id)
        {
            setTitle("Sample-okHttp");
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            mTv.setText("onError:" + e.getMessage());
        }

        @Override
        public void onResponse(String response, int id) {
            Log.e(TAG, "onResponse：complete");
            mTv.setText("onResponse:" + response);
        }

        @Override
        public void inProgress(float progress, long total, int id) {
            Log.e(TAG, "inProgress:" + progress);
            mProgressBar.setProgress((int) (100 * progress));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
